package ch.ffhs.bscinf2009.organizeanything.gui;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import ch.ffhs.bscinf2009.organizeanything.Environment;
import ch.ffhs.bscinf2009.organizeanything.R;
import ch.ffhs.bscinf2009.organizeanything.data.AbstractType;
import ch.ffhs.bscinf2009.organizeanything.data.Organizable;

/**
 * @author lir
 * Shows the screen with all the details of an instance listed
 */
public class OrganizableInstanceDetail extends Activity {
	private Organizable detail;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.organizable_instance_detail);

		detail = (Organizable) getIntent().getExtras()
				.getSerializable("detail");

		refresh();
	}

	private void refresh() {
		ListView listView = (ListView) findViewById(R.id.instance_detail);
		List<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();

		for (AbstractType type : detail.getProperties()) {
			HashMap<String, String> values = new HashMap<String, String>(1);
			values.put("item", type.displayValue());
			values.put("sub", type.getPropertyName());
			list.add(values);
		}

		SimpleAdapter adapter = new SimpleAdapter(this, list,
				R.layout.custom_row_view, new String[] { "item", "sub" },
				new int[] { R.id.item, R.id.subitem });

		// Assign adapter to ListView
		listView.setAdapter(adapter);
	}

	/**
	 * Deletes the current instance from the database
	 * @param view the view the method was called from
	 */
	public void functionRemove(View view) {
		List<Organizable> l = new ArrayList<Organizable>();
		l.add(detail);
		Environment.getInstance().getDB(this).deleteEntry(l);
		finish();
	}

	/**
	 * Shows the update screen for the current instance
	 * @param view the view the method was called from
	 */
	public void updateObject(View view) {
		final Intent i = new Intent(this, OrganizableManageObject.class);
		i.putExtra("detail", detail);
		startActivityForResult(i, 99);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case (99): {
			if (resultCode == Activity.RESULT_OK) {
				detail = (Organizable) data.getExtras().getSerializable(
						"udpateOrganizableObject");
			}
			break;
		}
		}
		refresh();
	}

}
